package it.sd.pwframework.admin.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedList;

public class ConverterUtility {

	public static String serialize(Object o ) throws Exception {
		
		String valore = null;
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    ObjectOutputStream out = new ObjectOutputStream(baos);
	    out.writeObject(o);
	    out.close();
	    valore = toAscii(baos.toByteArray());
	    baos.close();
	    
	    return valore;

	}
	
	public static Object deSerialize(String valore) throws Exception {
		
		byte[] array = toByte(valore);
		ByteArrayInputStream bais = new ByteArrayInputStream(array);
        ObjectInputStream in = new ObjectInputStream(bais);
        Object o = in.readObject();
        in.close();
        bais.close();
        
        return o;
	}

	private static String toAscii(byte[] array) {
		StringBuffer b = new StringBuffer();

		for (byte b1 : array) {
			int i = 128 + b1; 
			String valore = Integer.toHexString(i);
			if (valore.length()==1) b.append("0");
			b.append(valore);
		}
		
		return b.toString();
	}

	private static byte[] toByte(String valore) {
		byte[] b = new byte[valore.length()/2];
		for (int i = 0; i < b.length; i++) {
			int v = Integer.parseInt(valore.substring(i*2, i*2+2), 16);
			b[i] = (byte)(v-128);
		}
		return b;
	}

	public static void main(String[] args) {
		
		try {
			LinkedList<String> valori = new LinkedList<String>();
			valori.add("aa");
			valori.add("a|e");
			valori.add("a\\|\\\\ii||");
			valori.add("aeee");
			valori.add("aererer");
			 
			System.out.println(valori);
			String valore = serialize(valori);
			System.out.println(valore);
			
			Object o  = deSerialize(valore);
			System.out.println(o);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

}
